const webSocketFactory = {
  connectPath: '',
  userId: '',
  reConnectFlag: false,
  isConnect: true,
  timeout: 10000,
  timeoutObj: [],
  onmessageHandler: null,
  resetHeartCheck: (userId, websocket) => {
    webSocketFactory.userId = userId
    webSocketFactory.timeoutObj.forEach(a => clearTimeout(a))
    webSocketFactory.startHeartCheck(userId, websocket)
  },
  startHeartCheck: (userId, webSocketWrapper) => {
    webSocketFactory.timeoutObj && webSocketFactory.timeoutObj.forEach(a => clearTimeout(a))
    const aa = setTimeout(function () {
      // 这里发送一个心跳，后端收到后，返回一个心跳消息，
      console.log('发送心跳检测ping')
      // onmessage拿到返回的心跳就说明连接正常
      webSocketWrapper.send(JSON.stringify({ name: 'HEART_CHECK', data: userId + '心跳检测ping' }))
    }, webSocketFactory.timeout)
    webSocketFactory.timeoutObj.push(aa)
  },
  /**
   * 发起连接
   */
  connect (connectPath) { // 创建WebSocket
    webSocketFactory.connectPath = connectPath
    if (!('WebSocket' in window)) {
      alert('当前浏览器不支持WebSocket')
      return
    }
    const webSocket = new WebSocket(webSocketFactory.connectPath) // ws://HOST:PORT
    // webSocket.onopen = event => {
    //   console.log('websocket链接开启: ')
    // }
    // webSocket.onclose = event => {
    //   console.log('WebSocket连接关闭, 发起重连')
    // }
    // webSocket.onerror = event => {
    //   console.log('WebSocket通信异常, 发起重连')
    // }
    webSocket.onmessage = event => console.log('WebSocket接收到消息')
    const webSocketWrapper = {
      onopen (handler) { // 建立连接
        webSocket.onopen = handler
        return webSocketWrapper
      },
      onmessage (handler) { // 接收消息
        // webSocketFactory.onmessageHandler = handler
        webSocket.onmessage = handler
        return webSocketWrapper
      },
      onerror (handler) { // 通信异常
        webSocket.onerror = handler
        return webSocketWrapper
      },
      onclose (handler) { // 关闭连接
        webSocket.onclose = handler
        return webSocketWrapper
      },
      send (msg) { // 发送消息
        if (webSocket.readyState === WebSocket.OPEN) {
          webSocket.send(msg)
        } else {
          console.log('WebSocket连接已关闭！')
        }
      },
      close () { // 关闭连接
        if (webSocket.readyState === WebSocket.OPEN) {
          webSocket.close()
        } else {
          console.log('WebSocket连接已关闭！')
        }
      }
    }
    return webSocketWrapper
  }
}
export default webSocketFactory
